package com.fly.docker.web;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fly.core.entity.JsonResult;
import com.fly.docker.service.DockerService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.ImmutableList;
import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.DockerClient.ListImagesParam;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.Container;
import com.spotify.docker.client.messages.ContainerInfo;
import com.spotify.docker.client.messages.ContainerMount;
import com.spotify.docker.client.messages.ImageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/docker-sock")
@Api(tags = "docker-socket初始化")
public class DockerSockApi
{
    @Autowired
    DockerService dockerService;
    
    DockerClient dockerClient = new DefaultDockerClient("unix:///var/run/docker.sock");
    
    // @ApiOperation("create容器")
    @PostMapping("/create")
    public JsonResult<?> create(String key, String value)
        throws DockerException, InterruptedException
    {
        dockerService.process();
        return JsonResult.success("请求发送成功，docker请求异步执行中");
    }
    
    @ApiOperation("Unix socket")
    @ApiOperationSupport(order = 10)
    @GetMapping("/unix-sock")
    public JsonResult<?> sock()
        throws DockerException, InterruptedException
    {
        AtomicInteger count = new AtomicInteger();
        List<Container> containers = dockerClient.listContainers();
        containers.forEach(container -> log.info("{}. {} {}", count.incrementAndGet(), container.id(), container.names()));
        return JsonResult.success(containers);
    }
    
    @ApiOperation("mounts")
    @ApiOperationSupport(order = 20)
    @GetMapping("/mounts/{containerId}")
    public JsonResult<?> mounts(@PathVariable String containerId)
        throws DockerException, InterruptedException
    {
        ContainerInfo containerInfo = dockerClient.inspectContainer(containerId);
        ImmutableList<ContainerMount> mounts = containerInfo.mounts();
        List<String> collect = mounts.stream().map(m -> m.source()).sorted().collect(Collectors.toList());
        return JsonResult.success(RandomUtils.nextBoolean() ? mounts : collect);
    }
    
    @ApiOperation("搜索本地镜像")
    @ApiOperationSupport(order = 30)
    @GetMapping("/searchImage")
    public JsonResult<?> searchImage(String tag)
        throws DockerException, InterruptedException
    {
        // java.lang.NullPointerException: Null virtualSize
        int count = dockerClient.listImages(ListImagesParam.byName(tag)).size();
        return JsonResult.success(Collections.singletonMap("count", count));
    }
    
    @ApiOperation("查看镜像")
    @ApiOperationSupport(order = 40)
    @GetMapping("/inspectImage")
    public JsonResult<?> inspectImage(String imageId)
        throws DockerException, InterruptedException
    {
        // java.lang.NullPointerException: Null container
        ImageInfo info = dockerClient.inspectImage(imageId);
        return JsonResult.success(info);
    }
}
